package com.bjtu.ptsite.tracker.job;

import com.bjtu.ptsite.mapper.PeerMapper;
import com.bjtu.ptsite.mapper.TrackerMessageMapper;
import com.bjtu.ptsite.tracker.client.TrackerClient;
import com.bjtu.ptsite.tracker.entity.TrackerMessage;
import com.bjtu.ptsite.utils.TaskUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Zehao Wang, Junjie Zhang, Yutao Wei
 *
 */
@Slf4j
@Component
public class ConnectTorrentSyncJob {

    @Autowired
    private PeerMapper peerMapper;

    @Autowired
    private TrackerClient trackerClient;

    @Autowired
    private TrackerMessageMapper trackerMessageMapper;

    //定时任务，一小时一次

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void connectTorrentSyncJob() {

        List<Future<?>> futures = new ArrayList<>();

        List<TrackerMessage> trackerMessages = trackerMessageMapper.selectAllTorrents();
        log.info("开始执行定时任务：定时同步种子连接性");
        for (TrackerMessage trackerMessage : trackerMessages) {
            futures.add(TaskUtil.submit(() -> {
                boolean connected = trackerClient.isConnect(trackerMessage.getInfoHash());
                trackerMessage.setConnect(connected);
            }));
        }

        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (Exception e) {
                log.error("连接性检测任务失败或超时", e);
            }
        }

        for(TrackerMessage trackerMessage : trackerMessages){
            trackerMessageMapper.updateConnectStatus(trackerMessage);
        }
    }
}
